package com.mach.platform.controller;

import com.mach.platform.constants.CommonConstants;
import com.mach.platform.domain.Response;
import com.mach.platform.domain.base.Account;
import com.mach.platform.service.AccountService;
import com.mach.platform.utils.JsonUtils;
import com.mach.platform.utils.security.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;

/**
 * @author Anonymous
 * @Name
 * @Description: 用户控制器
 * @date 2018/04/03   21:44
 */
@Api(tags = { "用户管理接口" })
@RestController
@RequestMapping("$user")
public class AccountCtrl extends BaseCtrl<Account> {

	@Autowired
	private AccountService accountService;

	/**
	 * -- @GetMapping(value = "/xxx/{id}")
	 * -- @PathVariable(value = "id", required = false) Long id
	 * 单个数据 的接口
	 *
	 * @param id 数据的id
	 * @return
	 */
	@GetMapping(value = "/info/{id}")
	@Override
	public Response info (@PathVariable(value = "id", required = false) Long id) {

		return null;
	}

	@ApiOperation(value = "获取当前登录者的信息", produces = "application/json", notes = "无参数")
	@GetMapping(value = "/current")
	public Response curInfo ( ) {

		Account dbResult = accountService.info(SecurityUtils.getCurrentUser().getId());

		return Response.ok(dbResult);

	}

	/**
	 * 获取列表数据
	 * --@GetMapping(value = "/list")
	 * -- @PageableDefault(size = 25) Pageable pageable
	 *
	 * @param pageable
	 * @return
	 */
	@ApiOperation(value = "列表--分页", produces = "application/json", notes = "列表参数：size(每页数量),page(页码),searchParam(查询内容)")
	@GetMapping(value = "/list")
	@Override
	public Response list (@PageableDefault(size = 25) Pageable pageable, @RequestParam Map params) {

		Page<Account> result = accountService.list(pageable, params);

		return Response.ok(result);
	}

	/**
	 * -- @DeleteMapping("/del")
	 * -- @RequestBody Long[] ids
	 * 删除数据
	 *
	 * @param ids
	 * @return
	 */
	@ApiOperation(value = "删除", produces = "application/json")
	@DeleteMapping("/del")
	@Override
	public Response delete (@RequestBody Long[] ids) {

		Long curId = SecurityUtils.getCurrentUser().getId();

		if (Arrays.asList(ids).stream().anyMatch(item -> item.equals(1L))) {
			return Response.error("有一个账号很高级，任何人不能删除...");
		}

		if (Arrays.asList(ids).stream().anyMatch(item -> item.equals(curId))) {
			return Response.error("注意，不能删除当前登录用户");
		}

		Integer deleteFlag = accountService.delete(ids);

		return Response.ok(deleteFlag);
	}

	/**
	 * 保存一个 对象
	 * --@PostMapping("/save")
	 * --@RequestBody T t
	 *
	 * @param account
	 * @return
	 */
	@ApiOperation(value = "新增", produces = "application/json")
	@PostMapping("/save")
	@Override
	public Response save (@RequestBody Account account) {

		Account result = accountService.save(account);
		Map resultMap = JsonUtils.transBean2Map(result, new String[] { "password", "roles" });

		return Response.ok(resultMap);

	}

	/**
	 * 更新一个对象
	 * --@PutMapping("/upd")
	 * --@RequestBody T t
	 *
	 * @param account
	 * @return
	 */
	@ApiOperation(value = "修改保存", produces = "application/json")
	@PutMapping("/upd")
	@Override
	public Response update (@RequestBody Account account) {

		if (account.getId().equals(CommonConstants.ADMIN_ID) && !SecurityUtils.getCurrentUser().getId().equals(
				CommonConstants.ADMIN_ID)) {
			return Response.error("一般账号不能修改超级管理员账号！");
		}


		Account dbResult = accountService.update(account);

		return Response.ok(dbResult);
	}

	/**
	 * 上传文件数据
	 *
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public Response uploadFile (@RequestParam("file") MultipartFile file) {

		if (file == null) {
			return Response.error("上传文件为空，上传失败，请检查！");
		}

		Integer effections = 0;

		try {
			effections = accountService.uploadXlsFile(file.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return Response.ok(effections);
	}

	/**
	 * @return
	 */
	@RequestMapping(value = "/export", method = RequestMethod.POST)
	public void export (HttpServletResponse response) {

		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
		try {
			response.setHeader("Content-Disposition",
					"attachment; filename=" + URLEncoder.encode("用户导入数据模板", "UTF-8") + ".xlsx");

			@Cleanup OutputStream outputStream = response.getOutputStream();
			@Cleanup InputStream inputStream = ClassUtils.getDefaultClassLoader()
			                                             .getResourceAsStream("/static/model.xlsx");

			int len = -1;
			byte[] bytes = new byte[1024];

			while (( len = inputStream.read(bytes) ) != -1) {
				outputStream.write(bytes, 0, len);
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 修改密码
	 *
	 * @param id       用户id
	 * @param password 新密码
	 * @return Response
	 */
	@ApiOperation(value = "修改密码", produces = "application/json")
	@RequestMapping(value = "password", method = RequestMethod.POST)
	public Response changePassword (@ApiParam(value = "用户id") @RequestParam("id") Long id,
			@ApiParam(value = "新密码") @RequestParam("password") String password) {

		if (id.equals(CommonConstants.ADMIN_ID) && !SecurityUtils.getCurrentUser().getId().equals(CommonConstants.ADMIN_ID)) {

			return Response.error("一般账号不能修改超级管理员账号密码！");
		}

		Integer flag = accountService.changePassword(id, password);

		if (flag > 0) {
			return Response.ok(flag);
		} else {
			return Response.error("修改失败");
		}

	}

	@ApiOperation(value = "当前用户修改密码", produces = "application/json")
	@RequestMapping(value = "changePw", method = RequestMethod.POST)
	public Response changePassword2 (@ApiParam(value = "旧密码") @RequestParam("oldPw") String oldPw, @ApiParam(value = "新密码") @RequestParam("password") String password) {

		boolean compareResult = accountService.comparePassword(SecurityUtils.getCurrentUser().getId(), oldPw);

		if (!compareResult) {
			return Response.error("旧密码不正确，不能修改密码！");
		} else {
			accountService.changePassword(SecurityUtils.getCurrentUser().getId(), password);
			return Response.ok("更新成功");
		}
	}

	/**
	 * 移除当前部门的 用户关联
	 *
	 * @param ids  ids 数组
	 * @param type 操作类型，部门或者 岗位
	 * @return Response
	 */
	@ApiOperation(value = "移除部门用户", produces = "application/json", notes = "type 参数，手动拼接在url后传参")
	@DeleteMapping("remove")
	public Response removeOrgInfo (@ApiParam(required = true, value = "要移除部门的用户IDs") @RequestBody Long[] ids,
			@ApiParam(required = true, value = "移除类型，0为部门，1为岗位") @RequestParam("type") Integer type) {

		Integer flag = accountService.removeOrgOrPostInfo(ids, type);
		if (flag > 0) {
			return Response.ok(flag);
		} else {
			return Response.error("移除异常.");
		}

	}

	/**
	 * 获取角色对应的用户数据
	 *
	 * @param pageable 分页数据
	 * @param roleId   角色id
	 * @param searchParam 查询内容
	 * @return Response
	 */
	@ApiOperation(value = "获取角色对应的用户数据", produces = "application/json")
	@GetMapping("/roleUsers")
	public Response loadUsersByRoldId (@PageableDefault(size = 25) Pageable pageable,
			@ApiParam(value = "角色Id") @RequestParam("roldId") Long roleId,
			@ApiParam(value = "查询内容", required = false) @RequestParam(value = "searchParam", defaultValue = "", required = false) String searchParam) {

		Page<Map> dbResult = accountService.loadUserByRoleIdIn(pageable, searchParam,roleId);

		return Response.ok(dbResult);
	}

	/**
	 * 根据角色名称用户列表
	 * @param roleName
	 * @return
	 */
	@ApiOperation(value = "获取角色对应的用户数据", produces = "application/json")
	@PostMapping("/getAccount")
	public Response getAccountByRoleName (@PageableDefault(size = 25) Pageable pageable,@ApiParam(value = "角色名称")@RequestParam("roleName") String roleName) {

		Page<Map> accounts = accountService.getAccountByRoleName(pageable, roleName);

		return Response.ok(accounts);
	}

	/**
	 * 获取角色没有 关联的用户 数据
	 *
	 * @param pageable    分页数据
	 * @param roleId      角色id
	 * @param searchParam 查询内容
	 * @return Response
	 */
	@ApiOperation(value = "获取角色没有 关联的用户 数据", produces = "application/json")
	@PostMapping("/roleOutUsers")
	public Response loadUsersByRoldIdOut (@PageableDefault(size = 25) Pageable pageable,
			@ApiParam(value = "角色Id") @RequestParam("roldId") Long roleId,
			@ApiParam(value = "查询内容",required = false) @RequestParam(value = "searchParam",defaultValue = "",required = false) String searchParam) {

		Page<Map> dbResult = accountService.loadUserByRoleIdOut(pageable, searchParam, roleId);

		return Response.ok(dbResult);
	}

}
